/*
 * Package il.ac.biu.cs.grossmm.test.FooProtocol
 * File Session.java
 * 
 * This is a part of presence service framework API. 
 * See javadoc for more information.
 *  
 * Copyright (C) 2006 Grossmann Mark
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package il.ac.biu.cs.grossmm.foo.protocol;

import il.ac.biu.cs.grossmm.api.presence.Entity;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Session  {
	/**
	 * 
	 */
	protected final NioServer server;
	SocketChannel channel;
	StringBuffer inSb;
	StringBuffer outSb;
	ByteBuffer outBuf;
	String sessionId;
	
	ConcurrentHashMap<String, UserSession> userSessions 
		= new ConcurrentHashMap<String, UserSession>(1); 
	
	Lock lock = new ReentrantLock();
	
	Session() {
		// a direct session hack
		server = null;
	}

	Session(NioServer server, SocketChannel channel) {
		this.server = server;
		this.channel = channel;
		this.inSb = new StringBuffer();
		sessionId = ("xxxxxx"+Long.toString(this.server.sessionCounter++, 36)).substring(0, 6);
	}
	
	public UserSession creatUserSession(String user, Entity entity) {
		UserSession u = new UserSession(this, user, entity);
		return userSessions.putIfAbsent(user, u);
	}
	
	public UserSession getUserSession(String user) {
		return userSessions.get(user);
	}
	
	public Collection<UserSession> getUserSessions() {
		return userSessions.values();
	}
	
	public void removeUserSession(String user) {
		userSessions.remove(user);
	}
	
	void read() throws IOException {
		int nbytes = channel.read(this.server.inputByteBuffer);
		if( nbytes == -1 ) {
			terminate();
			return;
		}
		
		this.server.inputByteBuffer.flip();
		CharBuffer charBuffer = this.server.decoder.decode(this.server.inputByteBuffer);
		
		int n = charBuffer.limit();
		
		int start = 0;
		
		for( int i=0; i<n; i++ ) {
			if( charBuffer.get(i) == Message.MSG_DELIMETER ) {
				inSb.append(charBuffer, start, i);
				
				this.server.process(this, inSb.toString());

				inSb.setLength(0);
				start = i;
			}
		}
		
		// add the rest of the buffer (an incomplete message)
		// to the sb, so that we can append the rest of the
		// message later.
		inSb.append(charBuffer, start, n);
		this.server.inputByteBuffer.clear();
	}
	
	void write() {
		lock.lock();
		
		try {
			assert outBuf != null;
			
			channel.write(outBuf);
			channel.socket().getOutputStream().flush();
			
			if( outBuf.hasRemaining() )
				channel.keyFor(this.server.selector).interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
			else {
				channel.keyFor(this.server.selector).interestOps(SelectionKey.OP_READ);
				outBuf = null;
			}
			
		} catch (IOException e) {
			try {
				e.printStackTrace();
				channel.close();
			} catch (IOException e1) {
			}
		} finally {
			lock.unlock();
		}
	}
	
	void send(StringBuffer sb) {
		lock.lock();
		
		try {
			if( outSb == null ) 
				outSb = sb;
			else
				outSb.append(sb);
			
			if( outBuf == null ) {
				try {
					outBuf = ByteBuffer.wrap(outSb.toString().getBytes("utf-8"));
				} catch (UnsupportedEncodingException e) {
					assert false : "utf-8 undefined in java. hello world.";
				}
				
				outSb = null;
				
				write();
			} 
			
		} finally {
			lock.unlock();
		}
	}
	
	public void send(Response r) {
		send(r.toStringBuffer());
	}
	
	public void send(Request r) {
		send(r.toStringBuffer());
	}

	public void terminate()
	{
		this.server.terminating(this);
		try {
			channel.close();
		} catch (IOException e) {
		}
	}
}